package onlineclass.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class MyBatisUtil {

    private static SqlSessionFactory sessionFactory;

    private MyBatisUtil() {
    }

    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取SqlSess ion连接
    public static SqlSessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     * 新建session会话，并把session放在线程变量中
     */
    public static SqlSession get() {
        // 打开一个session会话
        SqlSession session = sessionFactory.openSession();
        return session;
    }

    public static SqlSession get(boolean autoCommit) {
        // 打开一个session会话
        SqlSession session = sessionFactory.openSession(autoCommit);
        return session;
    }

    //关闭资源
    public static void close(SqlSession session) {
        if (session != null) {
            session.commit();
            session.close();
        }
    }
}